
module Content
  # Document with extra action for fast prototyping of an app
  class CRUDController < DrunkenMaster::Widget

    def initialize document_class = nil
      @document_class = document_class || Document
      super()
    end

    def index
      e :div, :class => 'document_actions' do
        link "vytvořit", 'create', :class => 'create_document'
      end
      list
    end

    def create
      o = @document_class.new
      e :div, :class => 'document_actions' do
        link "zpět", '', :class => 'back_link'
      end
      form = form_for(o)
      form.action = callback(:insert)
    end

    def insert
      save
    end

    def read uuid
      p = Document.repository.get uuid
      e :div, :class => 'document_actions' do
        link "upravit", 'edit/'+p.uuid, :class => 'edit_link'
        add ', '
        link "smazat", 'remove/'+p.uuid, :class => 'edit_link'
      end
      add p.object.static
    end

    def edit uuid
      d = Document.get uuid
      e :div, :class => 'document_actions' do
        link "zpět", 'read/'+d.persisted.uuid, :class => 'back_link'
      end
      form = form_for(d)
      form.action = callback(:update)
    end

    def save
      params = context.request.params
      if params['uuid']
        doc = Document.get(params['uuid'])
      else
        doc = Magic.to_const(params['class']).new
      end
      p "setting params #{params.inspect}"
      doc.value = params

      p "saving"
      Document.repository.put(doc.persisted || doc)
      p 
      redirect url('/read/'+doc.persisted.uuid)
    end

    def update
      save
    end

    def remove uuid
      Document.remove uuid
    end

    def list

    end

  private

    def form_for o
      add DrunkenMaster::Form.new do
        if o.persisted
          e :input,
            :type => 'hidden',
            :name => 'uuid',
            :value => o.persisted.uuid
        end
        e :input,
          :type => 'hidden',
          :name => 'class',
          :value => o.class

        add o.editable

        e :input, :type => 'submit', :value => 'save'
      end
    end

  end
end